<?php session_start();?>
beacon=-1;
driveList = new Array();
driveList[0] = "All Files";
driveList[1] = "Home";
driveList[2] = "Drop Box";
driveList[3] = "Sky Drive";
driveList[4] = "Box";
driveList[5] = "Google Drive";

$.getScript('//js.live.net/v5.0/wl.js', function()
{
    // script is now loaded and executed.
    // put your dependent JS here.
});

$(document).ready(function() {

$('#0').click(function(){
$('#currentdrive').text('All'+' '+'Files');
$('#'+beacon).show();
$('#0').hide();
beacon=0;
var i=1;
while(i<=5)
{
if(i!=beacon)
$('#'+i).text(driveList[i]);
i++;
}
$('#filecontents').empty();
handleClientLoad();
});


//click to go home from any page
$('#1').click(function(){
$('#view').css('display','none');
$('#container').removeAttr('style');
$('#currentdrive').text('Home');
});

$('#2').click(function(){
$('#currentdrive').text('Drop'+' '+'Box');
$('#'+beacon).show();
$('#2').hide();
beacon=2;
var i=0;
while(i<=5)
{
if(i!=beacon || i!=2)
$('#'+i).text(driveList[i]);
i++;
}
$('#filecontents').empty();
});

$('#3').click(function(){
$('#currentdrive').text('SkyDrive');
$('#'+beacon).show();
$('#3').hide();
beacon=3;
var i=0;
while(i<=5)
{
if(i!=beacon || i!=3)
$('#'+i).text(driveList[i]);
i++;
}
$('#filecontents').empty();
});

$('#4').click(function(){
$('#currentdrive').text('Box');
$('#'+beacon).show();
$('#4').hide();
beacon=4;
var i=0;
while(i<=5)
{
if(i!=beacon || i!=4)
$('#'+i).text(driveList[i]);
i++;
}
$('#filecontents').empty();

<?php 
			$baseURL = "https://api.box.com/2.0";
		
			function get($url)
			{
				if(isset($_SESSION['box_access_token']))
				{
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer ".$_SESSION['box_access_token']));
					
					$data = curl_exec($ch);
					curl_close($ch);
				
					return json_decode($data);
				}
			}	
			
			$boxUserData = get($baseURL."/users/me");
			
			//echo "Box User Space = ".$boxUserData->space_amount;
			//echo "<br/>";
			//echo "Box User Used Space = ".$boxUserData->space_used;
			//echo "<br/>";
			//echo "Box Max Upload Size = ".$boxUserData->max_upload_size;
			
			function getFolderItems($id, $baseURL)
			{
				
				$boxFileData = get($baseURL."/folders/".$id."/items");
				//echo "<br/>";
				//echo "Box File Information ";
				
				//print_r($boxFileData);
				
				//$entries = $boxFileData->entries;
				echo '
						var header="<tr><td>#</td><td>File</td><td>Size</td><td>Download URL</td></tr>"; 
        				$("#filecontents").append(header); ';
          
				for ($i=0; $i<$boxFileData->total_count; $i++)
				{
					$file = $boxFileData->entries[$i];
					$filename = ($file->name); 
					$boxFileInfo = get($baseURL."/files/".$file->id);
					$filesize = $boxFileInfo->size;
					//$shared_link = $boxFileInfo->shared_link;
					//print_r($boxFileInfo->modified_at);
					
					
					echo '
					var row="<tr class=\'error\'><td>"+'.($i+1).'+"</td><td>'.$filename.'</td><td>"+
					'.$filesize.'+" KB</td><td><a href=\'http://www.google.com\'>Box</a></td></tr>";
                    $("#filecontents").append(row);
					';
				
				}
			}
			
			if(isset($_SESSION['box_access_token']))
				getFolderItems(0, $baseURL);

?>

});

$('#5').click(function(){
$('#currentdrive').text('GoogleDrive');
$('#'+beacon).show();
$('#5').hide();
beacon=5;
var i=0;
while(i<5)
{
if(i!=beacon)
$('#'+i).text(driveList[i]);
i++;
}
$('#filecontents').empty();
handleClientLoad();
});


$('#skydrive').click(function(){
$('#container').css('display','none');
$('#view').removeAttr('style');
$('#currentdrive').text('Sky Drive');
$('#3').hide();

if($('#'+beacon).is(":visible")==false)
{
$('#'+beacon).show();
}
beacon=3;
$('#filecontents').empty();

var client_id = "000000004C0DFC8A",
scope = ["wl.signin", "wl.basic", "wl.offline_access", "wl.skydrive", "wl.skydrive_update"],
redirect_uri = "https://thegodzilladrive.com/pennapps/bootstrap/callback.php";

if (WL.getSession() != null) {

            WL.api({ path: "/me/skydrive/quota", method: "GET" }).then(
                    function(response) {
                    	alert(response);
                        //quotaHolder.innerHTML = (JSON.stringify(response).replace(/,/g, ",\n"));
                    
                    },
                    function(response) {
                    	quotaHolder.innerHTML = ("Could not access quota, status = " +
                            JSON.stringify(response.error).replace(/,/g, ",\n"));
                    }
                );

            WL.api({ path: "/me/skydrive/my_documents", method: "GET" }).then(
                    function(response) {
                        filesHolder.innerHTML = (JSON.stringify(response).replace(/,/g, ",\n"));
                    },
                    function(response) {
                    	filesHolder.innerHTML = ("Could not access drive, status = " +
                            JSON.stringify(response.error).replace(/,/g, ",\n"));
                    }
                );
        }


});



$('#gdrive').click(function(){
$('#container').css('display','none');
$('#view').removeAttr('style');
$('#currentdrive').text('Google'+' '+'Drive');
$('#5').hide();

if($('#'+beacon).is(":visible")==false)
{
$('#'+beacon).show();
}
beacon=5;
$('#filecontents').empty();
handleClientLoad();
});

$('#box').click(function(){


<?php 
			$baseURL = "https://api.box.com/2.0";
		
			function get2($url)
			{
				if(isset($_SESSION['box_access_token']))
				{
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer ".$_SESSION['box_access_token']));
					
					$data = curl_exec($ch);
					curl_close($ch);
				
					return json_decode($data);
				}
			}	
			
			$boxUserData = get2($baseURL."/users/me");
			
			//echo "Box User Space = ".$boxUserData->space_amount;
			//echo "<br/>";
			//echo "Box User Used Space = ".$boxUserData->space_used;
			//echo "<br/>";
			//echo "Box Max Upload Size = ".$boxUserData->max_upload_size;
			
			function getFolderItems2($id, $baseURL)
			{
				
				$boxFileData = get2($baseURL."/folders/".$id."/items");
				//echo "<br/>";
				//echo "Box File Information ";
				
				//print_r($boxFileData);
				
				//$entries = $boxFileData->entries;
				echo '
						var header="<tr><td>#</td><td>File</td><td>Size</td><td>Download URL</td></tr>"; 
        				$("#filecontents").append(header); ';
          
				for ($i=0; $i<$boxFileData->total_count; $i++)
				{
					$file = $boxFileData->entries[$i];
					$filename = ($file->name); 
					$boxFileInfo = get2($baseURL."/files/".$file->id);
					$filesize = $boxFileInfo->size;
					//$shared_link = $boxFileInfo->shared_link;
					//print_r($boxFileInfo->modified_at);
					
					
					echo '
					var row="<tr class=\'error\'><td>"+'.($i+1).'+"</td><td>'.$filename.'</td><td>"+
					'.$filesize.'+" KB</td><td><a href=\'http://www.google.com\'>Box</a></td></tr>";
                    $("#filecontents").append(row);
					';
				
				}
			}
			
			if(isset($_SESSION['box_access_token']))
				getFolderItems2(0, $baseURL);

?>
$('#container').css('display','none');
$('#view').removeAttr('style');
$('#currentdrive').text('Box');
$('#4').hide();
if($('#'+beacon).is(":visible")==false)
{
$('#'+beacon).show();
}
beacon=4;
//$('#filecontents').empty();

});

$('#dropbox').click(function(){

<?php 

	
	if(!isset($_SESSION['state']))
	{
		$_SESSION['state'] = 1;
		echo 'window.location = "../bootstrap/dropbox.php";';
	}
	else if($_SESSION['state'] == -1)
	{
		$array = $_SESSION['dropbox']['contents'];
		$i = 0;
		foreach(array_keys($array) as $k)
		{
			$v = $array[$k];
			//echo "alert(".print_r($v).")";
			$filename = $v['path'];
			$filesize = $v['size'];
			echo '
						var header="<tr><td>#</td><td>File</td><td>Size</td><td>Download URL</td></tr>"; 
        				$("#filecontents").append(header); ';
			echo '
					var row="<tr class=\'error\'><td>'.($i+1).'</td><td>'.$filename.'</td><td>"+
					"'.$filesize.' KB</td><td><a href=\'http://www.google.com\'>Box</a></td></tr>";
                    $("#filecontents").append(row);
					';
			$i = $i + 1;
			
		}
	}
	else if ($_SESSION['state'] != 7)
	{
		$_SESSION['state'] = 7;
		echo 'window.location = "../bootstrap/dropbox.php";';
	}
	
	
	
?>

//window.location = '../bootstrap/dropbox.php';

$('#container').css('display','none');
$('#view').removeAttr('style');
$('#currentdrive').text('Drop Box');
$('#2').hide();
if($('#'+beacon).is(":visible")==false)
{
$('#'+beacon).show();
}
beacon=2;
//$('#filecontents').empty();
});


     var CLIENT_ID = '844331264844-vmf58hamkl26gsfoddopihro563fovo5.apps.googleusercontent.com';
      var SCOPES = 'https://www.googleapis.com/auth/drive';
	  var key='AIzaSyDxThnE58Fovs-PJZGFoO83I1EJHRz242M';
	  $('#viewall').click(function(){	  
	  
	  $('#container').css('display','none');
	  $('#view').removeAttr('style');
	  $('#0').hide();
	  $('#currentdrive').text('All Files');

	 if($('#'+beacon).is(":visible")==false)
	 {
	  $('#'+beacon).show();
	 }
	  beacon =0;
	  $('#filecontents').empty();
	  handleClientLoad();
});
      /**
       * Called when the client library is loaded to start the auth flow.
       */
      function handleClientLoad() {
      gapi.client.setApiKey(key);
        window.setTimeout(checkAuth, 1);
      }

      /**      
       * Check if the current user has authorized the application.
       */
      function checkAuth() {
        gapi.auth.authorize(
            {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},
            handleAuthResult);
      }

      /**
       * Called when authorization server replies.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {
        /*var authButton = document.getElementById('authorizeButton');
        var filePicker = document.getElementById('filePicker');
        var fileListBtn= document.getElementById('listFilesButton');
        
        authButton.style.display = 'none';
        filePicker.style.display = 'none';
        fileListBtn.style.display= 'none';*/
        if (authResult && !authResult.error) {
          // Access token has been successfully retrieved, requests can be sent to the API.
          //filePicker.style.display = 'block';
          //filePicker.onchange = uploadFile;

          //fileListBtn.style.display= 'block';
          //fileListBtn.onclick = makeApiCall;
          makeApiCall();
          printAbout();
        } else {
          // No access token could be retrieved, show the button to start the authorization flow.
         // authButton.style.display = 'block';
          //authButton.onclick = function() {
              gapi.auth.authorize(
                  {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false},
                  handleAuthResult);
          //};
        }
      }

      /**
       * Start the file upload.
       *
       * @param {Object} evt Arguments from the file selector.
       */
      function uploadFile(evt) {
        gapi.client.load('drive', 'v2', function() {
          var file = evt.target.files[0];
          insertFile(file);
        });
      }
      
      function printAbout() {
      gapi.client.load('drive', 'v2', function() {
      var request = gapi.client.drive.about.get();
    request.execute(function(resp) {
    console.log('Current user name: ' + resp.name);
    console.log('Root folder ID: ' + resp.rootFolderId);
    console.log('Total quota (bytes): ' + resp.quotaBytesTotal);
    console.log('Used quota (bytes): ' + resp.quotaBytesUsed);
    
    var percent= Math.floor(100*(resp.quotaBytesUsed/resp.quotaBytesTotal));
    console.log(percent);
    $('.gdrivebar').css('width',percent);
    $('.gdriveul').css('display','block');
    $('.drivetxt').text(percent + '% used');
});
});      
}

function makeApiCall() {
        gapi.client.load('drive', 'v2', function() {
         // var request = gapi.client.drive.files.list ( 'params': {'maxResults': 5 } );
          var request = gapi.client.request({
        'path': '/drive/v2/files',
        'method': 'GET',
        'params': {'maxResults': 10}
        });
          request.execute(function(resp) {       
          var header="<tr><td>#</td><td>File</td><td>Size</td><td>Download URL</td></tr>"; 
          $("#filecontents").append(header);  
            for (i=0; i<resp.items.length; i++) {
                    var titulo = resp.items[i].title;
                    var fechaUpd = resp.items[i].modifiedDate;
                    var userUpd = resp.items[i].lastModifyingUserName;
                    var fileSize = Math.floor(resp.items[i].fileSize/1024);
                    var mimeType=resp.items[i].mimeType;
                    var fileId=resp.items[i].id;
                    var downloadUrl=resp.items[i].alternateLink;
                    var fileInfo = document.createElement('li');

                    
       
       
       var row="<tr class='success'><td>"+(i+1)+"</td><td>"+titulo+"</td><td>"+fileSize+" KB</td><td><a href='"+downloadUrl+"'>GDrive</a></td></tr>";
                    $("#filecontents").append(row);
                    //fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd +' ,'+fileSize+', '+mimeType+' ,'+fileId));                
                    //document.getElementById('content').appendChild(fileInfo);
            }
          });        
        });
      }

      /**
       * Insert new file.
       *
       * @param {File} fileData File object to read data from.
       * @param {Function} callback Function to call when the request is complete.
       */
      function insertFile(fileData, callback) {
        const boundary = '-------314159265358979323846';
        const delimiter = "\r\n--" + boundary + "\r\n";
        const close_delim = "\r\n--" + boundary + "--";

        var reader = new FileReader();
        reader.readAsBinaryString(fileData);
        reader.onload = function(e) {
          var contentType = fileData.type || 'application/octet-stream';
          var metadata = {
            'title': fileData.name,
            'mimeType': contentType
          };

          var base64Data = btoa(reader.result);
          var multipartRequestBody =
              delimiter +
              'Content-Type: application/json\r\n\r\n' +
              JSON.stringify(metadata) +
              delimiter +
              'Content-Type: ' + contentType + '\r\n' +
              'Content-Transfer-Encoding: base64\r\n' +
              '\r\n' +
              base64Data +
              close_delim;

          var request = gapi.client.request({
              'path': '/upload/drive/v2/files',
              'method': 'POST',
              'params': {'uploadType': 'multipart'},
              'headers': {
                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
              },
              'body': multipartRequestBody});
          if (!callback) {
            callback = function(file) {
              console.log(file)
            };
          }
          request.execute(callback);
        }
      }
    
    });
